package zyz.framework.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {
    private static final Pattern URL = Pattern.compile(
            "^((https|http|ftp|rtsp|mms)?://)"
                    + "+(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?"
                    + "(([0-9]{1,3}\\.){3}[0-9]{1,3}"
                    + "|"
                    + "([0-9a-z_!~*'()-]+\\.)*"
                    + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\."
                    + "[a-z]{2,6})"
                    + "(:[0-9]{1,4})?"
                    + "((/?)|"
                    + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$", Pattern.CASE_INSENSITIVE
    );
    private static final Pattern EMAIL = Pattern.compile("^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$");
    private static final Pattern NUMERIC = Pattern.compile("^[0-9]+$");
    private static final Pattern MONEY = Pattern.compile("^[0-9]+$|^[0-9]+\\.[0-9]{1,6}$");
    private static final Pattern CH_CHAR = Pattern.compile("^[\u4e00-\u9fa5]+$");
    private static final Pattern PHONE = Pattern.compile("^1[3|4|5|7|8]([0-9])\\d{8}$");
    private static final Pattern TELPHONE = Pattern.compile("^(0[0-9]{2,4}-?[0-9]{7,8})|(1[3|4|5|7|8][0-9]{9})$");

    public static boolean checkUrl(String url) {
        Matcher m = URL.matcher(url);
        return m.matches();
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static Boolean checkEmail(String email) {
        Matcher m = EMAIL.matcher(email);
        return m.matches();
    }

    /**
     * 验证手机号
     *
     * @param phone
     * @return
     */
    public static Boolean checkPhone(String phone) {
        Matcher m = PHONE.matcher(phone);
        return m.matches();
    }

    /**
     * 验证固话和手机
     */
    public static Boolean checkTelPhone(String tel) {
        Matcher m = TELPHONE.matcher(tel);
        return m.matches();
    }

    /**
     * 是否是中文字符
     *
     * @param str
     * @return
     */
    public static boolean is_chinese(String str) {
        if (str == null) {
            return false;
        }
        Matcher result = CH_CHAR.matcher(str);
        return result.matches();
    }

    /**
     * @param str
     * @return
     * @Description: 判断字符串是否为数字
     */
    public static boolean isNumeric(String str) {
        Matcher isNum = NUMERIC.matcher(str);
        if (isNum.matches()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 是否为金额
     *
     * @param str
     * @return
     */
    public static boolean isMoney(String str) {
        return MONEY.matcher(str).matches();
    }

    /**
     * 字符串按指定符号分割为数组
     *
     * @param str
     * @param Symbol
     * @return
     * @throws Exception
     */
    public static String[] split(String str, String symbol) throws Exception {
        if (str.length() < 1 || symbol.length() < 1) {
            try {
                throw new Exception("字符错误");
            } catch (Exception e) {
                throw new Exception(e);
            }
        }
        String[] strSplit = str.split(symbol);
        return strSplit;
    }

    /**
     * 是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return org.apache.commons.lang.StringUtils.isEmpty(str);
    }

    /**
     * 是否不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }


    /**
     * 生成订单序列号
     * 日期加上(currentNum+1) pg: 201506160001
     *
     * @return
     */
    public static String generateSerialno(int currentNum) {
        String nextNumStr = String.valueOf(currentNum + 1);
        while (nextNumStr.length() < 4) {
            nextNumStr = "0" + nextNumStr;
        }
        return DateUtil.getCurrentDateStr() + nextNumStr;
    }

    /**
     * 将list转成String,并按impStr进行分隔
     *
     * @param objList
     * @param impStr
     * @return
     */
    public static String importStr(List<?> objList, String impStr) {
        String resultStr = "";
        for (Object obj : objList) {
            if (obj == null) {
                continue;
            }
            if ("".equals(resultStr)) {
                resultStr = obj.toString();
            } else {
                resultStr += impStr + obj.toString();
            }
        }
        return resultStr;
    }

    /**
     * 生成16位订单序列号
     * 日期加上(currentNum+1) pg: 201506160001
     *
     * @return
     */
    public static String getSerialno() {
        String base = UUID.randomUUID().toString();
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static List<String> getImageSrc(String htmlStr) {
        Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
        Matcher m = p.matcher(htmlStr);
        List<String> srcs = new ArrayList<String>();
        while (m.find()) {
            srcs.add(m.group(1));
        }
        return srcs;
    }

    /**
     * 将对象转化成String 进行比较
     *
     * @param fstObj
     * @param secObj
     * @return
     */
    public static boolean isEqual(Object fstObj, Object secObj) {
        if (fstObj == null && secObj == null) {
            return true;
        }
        if (fstObj == null || secObj == null) {
            return false;
        }
        return fstObj.toString().equals(secObj.toString());
    }

    /**
     * 截取limitLength长度的字符串
     *
     * @param str
     * @param limitLength
     * @return
     */
    public static String subString(String str, int limitLength) {
        return isNotEmpty(str) && str.length() > limitLength ? str.substring(0, limitLength) : str;
    }

    /**
     * 字符串编码
     *
     * @param sStr
     * @param sEnc
     * @return String
     */
    public static String encode(String sStr, String sEnc) {
        String sReturnCode = sStr;
        try {
            sReturnCode = URLEncoder.encode(sStr, sEnc);
        } catch (UnsupportedEncodingException ex) {
        }
        return sReturnCode;
    }

    /**
     * 字符串解码
     *
     * @param sStr
     * @param sEnc
     * @return String
     */
    public static String decode(String sStr, String sEnc) {
        String sReturnCode = sStr;
        try {
            sReturnCode = URLDecoder.decode(sStr, sEnc);
        } catch (UnsupportedEncodingException ex) {
        }
        return sReturnCode;
    }

    /**
     * 生成指定长度的随机数
     *
     * @param length
     * @return
     */
    public static String random(int length) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < length; i++) {
            result.append(new Random().nextInt(9));
        }

        return result.toString();
    }


    /**
     * 生成流水号（20位）
     *
     * @param userId
     * @return
     */
    public static String generateNid(Long userId) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSS");
        String userIdStr = userId.toString();
        if (userIdStr == null || userIdStr.length() == 0) {
            userIdStr = random(2);
        } else if (userIdStr.length() == 1) {
            userIdStr = random(1) + userIdStr;
        } else if (userIdStr.length() > 2) {
            userIdStr = userIdStr.substring(userIdStr.length() - 2, userIdStr.length());
        }
        return dateFormat.format(new Date()) + random(3) + userIdStr;
    }
}
